<?php


namespace Aoe\Emulator\Pascal;


use Aoe\Emulator\Schema\Element\Independent;
use Aoe\Database\Operator;
use PDO;
use function convert_int;

class Integer extends Pascal
{
    public static function rand(Independent $element): int
    {
        $min = intval($element->get(self::MIN, 0));
        $max = intval($element->get(self::MAX, 255));
        return $max >= $min ? rand($min, $max) : 0;
    }
    
    protected function bind($op = null): int
    {
        return PDO::PARAM_INT;
    }
    
    public function afterLoad($value): int
    {
        return (int)$value;
    }
    
    protected function valid_core(mixed &$value, string $operator = '=', bool $calculate = true): bool
    {
        return convert_int($value);
    }

    /**
     * @param int $value
     * @return bool
     */
    protected function valid_rules(mixed $value): bool
    {
        if ($this->element->has(self::MIN) && $value < intval($this->element->get(self::MIN))) return false;
        if ($this->element->has(self::MAX) && $value > intval($this->element->get(self::MAX))) return false;
        return parent::valid_rules($value);
    }

    protected function _calculators(): array
    {
        return ['++', '--', '+', '-', '*', '/', '%', '~', '|', '&', '<<', '>>', Operator::RAND_OPERATOR];
    }
    
    protected function compares(): array
    {
        return $this->math_compares();
    }
}
